package com.zjdiepu.www.commpent.handler;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.zjdiepu.www.base.core.BaseException;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.common.consts.RedisKeyPrefix;
import com.zjdiepu.www.commpent.RedisObjectClient;
import com.zjdiepu.www.config.AppProperty;
import com.zjdiepu.www.model.base.dto.SysUser;

/**
 * 项目名称：diepu-parent-rest <br/> 
 * 类名称：TokenUserHelper <br/>  
 * 类描述： token保存用户工具<br/>    
 * 创建人：xiongxiaotun <br/> 
 * 创建时间：2017年6月5日 上午11:45:17  <br/>   
 * 修改人：xiongxiaotun <br/> 
 * 修改时间：2017年6月5日 上午11:45:17   <br/>  
 * 修改备注：    <br/> 
 * @version V1.0   <br/>
 */
@Component
public class TokenUserHelper {
	private final Logger logger = LoggerFactory.getLogger(TokenUserHelper.class);
	@Resource
	private TokenHelper tokenHelper;
	@Resource
	private RedisObjectClient redisObjectClient;
	@Resource
	private AppProperty appProperty;
	
	/**
	 * @author xiongxiaotun <br/>
	 * @Title: exprieToken  <br/>
	 * @Description: 刷新登录凭据 <br/>
	 * @version V1.0  <br/>
	 */
	public void exprieToken(){
		String token = TokenHelper.getToken();
		if(StringUtils.isNotBlank(token)) {
			Long tokenExpire = appProperty.getTokenExpire();
			redisObjectClient.expire(token, tokenExpire);//uuid
			redisObjectClient.expire(token, tokenExpire, RedisKeyPrefix.PUBLIC_KEY);//publicKey
			SysUser sysUser = getUser();
			if(sysUser != null && StringUtils.isNotBlank(sysUser.getId())) {
				redisObjectClient.expire(sysUser.getId(), tokenExpire);//sysUser
				redisObjectClient.expire(sysUser.getId(), tokenExpire, RedisKeyPrefix.TOKENS);//tokens
			}
		}
	}
	
	/**
	 * @author xiongxiaotun <br/>
	 * @Title: delUser  <br/>
	 * @Description: 删除用户,刷新缓存  <br/>
	 * @param sysUser
	 * @version V1.0  <br/>
	 */
    public void delUser(SysUser sysUser) {
    	if(sysUser == null || StringUtils.isBlank(sysUser.getId())){
    		throw new BaseException(ResultFlagType.PARAM_EMPTY.getCode().toString(), ResultFlagType.PARAM_EMPTY.getValue());
    	}
    	String uuid = sysUser.getId();
    	redisObjectClient.del(uuid); //sysUser
    	List<String> tokens = redisObjectClient.get(uuid, RedisKeyPrefix.TOKENS);
    	for(String token : tokens) {
    		redisObjectClient.del(token); //uuid
    		redisObjectClient.del(token, RedisKeyPrefix.PUBLIC_KEY); //publicKey
    	}
    	redisObjectClient.del(uuid, RedisKeyPrefix.TOKENS);//tokens
    }
	
	/**
	 * @author xiongxiaotun <br/>
	 * @Title: delUser  <br/>
	 * @Description: 删除用户  <br/>
	 * @version V1.0  <br/>
	 */
    public void delUser() {
    	String token = TokenHelper.getToken();
    	if(StringUtils.isBlank(token)) {
    		throw new BaseException(ResultFlagType.ACCESS_DENIED.getCode().toString(), ResultFlagType.ACCESS_DENIED.getValue());
		}
    	SysUser sysUser = getUser();
    	if(sysUser == null || StringUtils.isBlank(sysUser.getId())){
    		throw new BaseException(ResultFlagType.ACCESS_DENIED.getCode().toString(), ResultFlagType.ACCESS_DENIED.getValue());
    	}
    	redisObjectClient.del(token);//uuid
    	redisObjectClient.del(token, RedisKeyPrefix.PUBLIC_KEY);//公钥
    	delToken(sysUser.getId(), token);//token
    }
	
	/**
	 * @author xiongxiaotun <br/>
	 * @Title: cacheUser  <br/>
	 * @Description: 缓存用户  <br/>
	 * @param token
	 * @param sysUser
	 * @version V1.0  <br/>
	 */
    public void cacheUser(String token, SysUser sysUser) {
    	if(sysUser == null || StringUtils.isBlank(sysUser.getId()) || StringUtils.isBlank(token)) {
			throw new BaseException(ResultFlagType.PARAM_EMPTY.getCode().toString(), ResultFlagType.PARAM_EMPTY.getValue());
		}
    	String uuid = sysUser.getId();
    	cacheId(token, uuid);
    	cacheUser(sysUser);
    	cacheToken(uuid, token);
    }

	
	/**
	 * @author xiongxiaotun <br/>
	 * @Title: getUser  <br/>
	 * @Description: 获取用户  <br/>
	 * @return
	 * @version V1.0  <br/>
	 */
    public SysUser getUser() {
    	String token = TokenHelper.getToken();
    	if(StringUtils.isBlank(token)) {
    		throw new BaseException("999", "需要登录凭据才能访问");
    	}
    	String uuid = redisObjectClient.get(token);
        if (StringUtils.isBlank(uuid)) { 
        	redisObjectClient.del(token);//uuid
        	redisObjectClient.del(token, RedisKeyPrefix.PUBLIC_KEY);//公钥
        	throw new BaseException(ResultFlagType.ACCESS_DENIED.getCode().toString(), ResultFlagType.ACCESS_DENIED.getValue());
        }
        SysUser sysUser = redisObjectClient.get(uuid);
        if(sysUser == null){
        	redisObjectClient.del(token);//uuid
        	redisObjectClient.del(token, RedisKeyPrefix.PUBLIC_KEY);//公钥
        	delToken(uuid, token);//token
        	throw new BaseException(ResultFlagType.ACCESS_DENIED.getCode().toString(), ResultFlagType.ACCESS_DENIED.getValue());
        }
    	logger.debug("获取后台登录用户信息成功......");
    	return sysUser;
    }

//   ==========================================基础工具方法============================== 
    
    /**
	 * @author xiongxiaotun <br/>
	 * @Title: cacheToken  <br/>
	 * @Description: 保存用户：uuid <-> token <br/>
	 * @param token
	 * @param userUuid
	 * @version V1.0  <br/>
	 */
	public void cacheToken(String userUuid, String token){
		if(StringUtils.isBlank(userUuid) || StringUtils.isBlank(token) ) {
			throw new BaseException(ResultFlagType.PARAM_EMPTY.getCode().toString(), ResultFlagType.PARAM_EMPTY.getValue());
		}
		List<String> tokens = redisObjectClient.get(userUuid, RedisKeyPrefix.TOKENS);
		if(CollectionUtils.isEmpty(tokens)) {
			tokens = new ArrayList<String>();
		}
		tokens.add(token);
		redisObjectClient.del(userUuid, RedisKeyPrefix.TOKENS);
		redisObjectClient.putExpire(userUuid, tokens, appProperty.getTokenExpire(), RedisKeyPrefix.TOKENS);
	}
	
	/**
	 * @author xiongxiaotun <br/>
	 * @Title: delToken  <br/>
	 * @Description: 删除用户：uuid <-> tokens <br/>
	 * @param token
	 * @param userUuid
	 * @version V1.0  <br/>
	 */
	public void delToken(String userUuid, String token){
		if(StringUtils.isBlank(userUuid) || StringUtils.isBlank(token) ) {
			throw new BaseException(ResultFlagType.PARAM_EMPTY.getCode().toString(), ResultFlagType.PARAM_EMPTY.getValue());
		}
		List<String> tokens = redisObjectClient.get(userUuid, RedisKeyPrefix.TOKENS);
		if(CollectionUtils.isEmpty(tokens)) {
			tokens = new ArrayList<String>();
		}
		tokens.remove(token);
		redisObjectClient.del(userUuid, RedisKeyPrefix.TOKENS);
		redisObjectClient.put(userUuid, tokens, RedisKeyPrefix.TOKENS);
	}
	
	/**
	 * @author xiongxiaotun <br/>
	 * @Title: cacheUser  <br/>
	 * @Description: 保存用户：uuid <-> sysUser <br/>
	 * @param token
	 * @param userUuid
	 * @version V1.0  <br/>
	 */
	public void cacheUser(SysUser sysUser){
		if(sysUser == null || StringUtils.isBlank(sysUser.getId())) {
			throw new BaseException(ResultFlagType.PARAM_EMPTY.getCode().toString(), ResultFlagType.PARAM_EMPTY.getValue());
		}
		redisObjectClient.del(sysUser.getId());
		redisObjectClient.putExpire(sysUser.getId(), sysUser, appProperty.getTokenExpire());
	}
	
	/**
	 * @author xiongxiaotun <br/>
	 * @Title: cacheId  <br/>
	 * @Description: 保存用户：token <-> uuid <br/>
	 * @param token
	 * @param userUuid
	 * @version V1.0  <br/>
	 */
	public void cacheId(String token, String userUuid){
		if(StringUtils.isBlank(token) || StringUtils.isBlank(userUuid)) {
			throw new BaseException(ResultFlagType.PARAM_EMPTY.getCode().toString(), ResultFlagType.PARAM_EMPTY.getValue());
		}
		redisObjectClient.del(token);
		redisObjectClient.putExpire(token, userUuid, appProperty.getTokenExpire());
	}
	
}
